using MauiApp.Models;
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Storage;
using System.Net.Http.Headers;
using MauiApp.Services;
using System.Net;

namespace MauiApp.Services
{
    public class ApiService : BaseService, IApiService
    {
        private readonly HttpClient _httpClient;
        private string _authToken = string.Empty;
        private const string UsernameKey = "CachedUsername";
        private const string PasswordKey = "CachedPassword";
        private const string LastLoginSuccessKey = "LastLoginSuccess";
        private string _currentUsername = string.Empty;
        private string _currentUserId = string.Empty;

        public ApiService()
        {
            // 使用基础类中的ApiBaseUrl属性
            _httpClient = new HttpClient
            {
                BaseAddress = new Uri(ApiBaseUrl)
            };
        }



        // 登录方法实现
        public async Task<LoginResponse?> LoginAsync(LoginRequest request)
        {
            try
            {
                // 记录请求信息用于调试
                var url = "auth/login";
                var fullUrl = $"{_httpClient.BaseAddress}{url}";
                LogHelper.Info($"发起登录请求到: {fullUrl}");
                LogHelper.Info($"请求用户名: {request.Username}");
                
                var response = await _httpClient.PostAsJsonAsync(url, request);
                
                // 记录响应状态
                LogHelper.Info($"登录请求响应状态码: {response.StatusCode}");
                
                if (response.IsSuccessStatusCode)
                {
                    var loginResponse = await response.Content.ReadFromJsonAsync<LoginResponse>();
                    
                    if (loginResponse != null)
                    {
                        LogHelper.Info($"登录响应成功: {loginResponse.Success}, 消息: {loginResponse.Message}");
                        
                        if (loginResponse.Success)
                        {
                            // 保存认证令牌
                            _authToken = loginResponse.Token ?? string.Empty;
                            LogHelper.Info($"成功获取认证令牌，长度: {_authToken.Length}");
                            
                            // 在HttpClient中设置认证头
                            if (!string.IsNullOrEmpty(_authToken))
                            {
                                _httpClient.DefaultRequestHeaders.Authorization = 
                                    new AuthenticationHeaderValue("Bearer", _authToken);
                            }
                            
                            // 保存当前用户名和用户ID
                            _currentUsername = request.Username;
                            // 使用UserDto中的Id（整数类型）
                            if (loginResponse.User != null)
                            {
                                _currentUserId = loginResponse.User.Id.ToString(); // 将整数ID转换为字符串保存
                                LogHelper.Info($"成功获取用户信息: ID={loginResponse.User.Id}, Username={loginResponse.User.Username}");
                            }
                            else
                            {
                                _currentUserId = "0"; // 默认值，确保是字符串格式的整数
                                LogHelper.Warn("登录响应中不包含用户信息");
                            }
                            
                            // 缓存用户名和密码
                            await CacheCredentialsAsync(request.Username, request.Password);
                            await SecureStorage.SetAsync(LastLoginSuccessKey, DateTime.Now.ToString());
                        }
                    }
                    else
                    {
                        LogHelper.Warn("无法解析登录响应内容");
                    }
                    
                    return loginResponse;
                }
                else
                {
                    // 获取详细的错误内容
                    var errorContent = await response.Content.ReadAsStringAsync();
                    LogHelper.Error($"登录失败: {response.StatusCode}, 错误内容: {errorContent}");
                    return null;
                }
            }
            catch (HttpRequestException ex)
            {
                LogHelper.Error($"HTTP请求异常: {ex.Message}");
                LogHelper.Error($"请求URL: {_httpClient.BaseAddress}auth/login");
                LogHelper.Error($"异常详情: {ex.ToString()}");
                
                // 区分连接错误和其他HTTP异常
                if (ex.InnerException is System.Net.Sockets.SocketException socketEx)
                {
                    LogHelper.Error($"网络连接异常: {socketEx.SocketErrorCode}, {socketEx.Message}");
                }
                
                return null;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"登录过程中发生未知错误: {ex.Message}");
                LogHelper.Error($"异常详情: {ex.ToString()}");
                return null;
            }
        }
        
        // 获取当前登录状态
        public bool IsLoggedIn => !string.IsNullOrEmpty(_authToken) && !string.IsNullOrEmpty(_currentUserId) && _currentUserId != "0";
        
        // 获取当前认证令牌
        public string GetAuthToken()
        {
            return _authToken;
        }
        
        // 获取当前用户名
        public string GetCurrentUsername()
        {
            return _currentUsername;
        }
        
        // 退出登录
        public void Logout()
        {
            _authToken = string.Empty;
            _currentUsername = string.Empty;
            _currentUserId = string.Empty;
            _httpClient.DefaultRequestHeaders.Authorization = null;
            
            // 清除缓存的凭证
            SecureStorage.Remove(UsernameKey);
            SecureStorage.Remove(PasswordKey);
            SecureStorage.Remove(LastLoginSuccessKey);
        }
        
        // 缓存凭证到安全存储
        private async Task CacheCredentialsAsync(string username, string password)
        {
            try
            {
                await SecureStorage.SetAsync(UsernameKey, username);
                await SecureStorage.SetAsync(PasswordKey, password);
            }
            catch (Exception ex)
            {
                LogHelper.Error($"缓存凭证失败: {ex.Message}");
            }
        }
        
        // 尝试自动登录
        public async Task<bool> TryAutoLoginAsync()
        {
            try
            {
                var username = await SecureStorage.GetAsync(UsernameKey);
                var password = await SecureStorage.GetAsync(PasswordKey);
                
                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    var response = await LoginAsync(new LoginRequest
                    {
                        Username = username,
                        Password = password
                    });
                    
                    return response != null && response.Success;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"自动登录失败: {ex.Message}");
            }
            
            return false;
        }
        

        
        // 获取当前登录的用户ID
        public string GetCurrentUserId()
        {
            // 防御性编程：确保返回有效的用户ID
            if (!string.IsNullOrEmpty(_currentUserId) && _currentUserId != "0")
            {
                return _currentUserId;
            }
            // 如果当前存储的用户ID无效，尝试从App.CurrentUserId获取
            else if (!string.IsNullOrEmpty(App.CurrentUserId) && App.CurrentUserId != "0")
            {
                // 同时更新内部存储，避免重复回退
                _currentUserId = App.CurrentUserId;
                return _currentUserId;
            }
            // 如果所有尝试都失败，返回一个默认值（但不应该发生）
            else
            {
                LogHelper.Warn("ApiService: 获取用户ID失败，返回默认值 '0'");
                return "0";
            }
        }
        
        // 获取单个文件信息
        public async Task<FileWithLastTimestampResponse?> GetFileByIdAsync(long fileId)
        {
            try
            {
                var url = $"file/{fileId}";
                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadFromJsonAsync<FileWithLastTimestampResponse>();
                }
                else
                {
                    LogHelper.Error($"获取文件信息失败: {response.StatusCode}");
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"获取文件信息时发生异常: {ex.Message}");
                return null;
            }
        }
       
        // 注意：此方法未被使用，保留是为了兼容性
        [Obsolete("Use LoginAsync(LoginRequest) instead")]
        public async Task<LoginResult> LoginAsync(string username, string password)
        {
            try
            {
                var loginResponse = await LoginAsync(new LoginRequest { Username = username, Password = password });
                
                if (loginResponse != null && loginResponse.Success)
                {
                    return new LoginResult
                    {
                        Success = true,
                        User = loginResponse.User
                    };
                }
                else
                {
                    return new LoginResult
                    {
                        Success = false,
                        ErrorMessage = loginResponse?.Message ?? "登录失败"
                    };
                }
            }
            catch (Exception ex)
            {
                return new LoginResult
                {
                    Success = false,
                    ErrorMessage = $"连接错误: {ex.Message}"
                };
            }
        }

        // 获取所有文件类型
        public async Task<List<TypesModel>> GetFileTypesAsync()
        {
            string responseContent = string.Empty;
            try
            {
                LogHelper.Debug($"[GetFileTypesAsync] 正在调用API: file/types, BaseUrl: " + _httpClient.BaseAddress);
                
                // 先检查服务器是否可访问
                // 修复URL构建：BaseUrl已经包含""，所以这里不需要再加
                var pingResponse = await _httpClient.GetAsync("file/types", HttpCompletionOption.ResponseHeadersRead);
                LogHelper.Debug($"[GetFileTypesAsync] 收到API响应，状态码: " + pingResponse.StatusCode);
                
                if (!pingResponse.IsSuccessStatusCode)
                {
                    LogHelper.Warn($"[GetFileTypesAsync] API调用失败: StatusCode={pingResponse.StatusCode}, Reason={pingResponse.ReasonPhrase}");
                    return new List<TypesModel>();
                }
                
                // 读取响应内容
                responseContent = await pingResponse.Content.ReadAsStringAsync();
                LogHelper.Debug($"[GetFileTypesAsync] API响应内容: " + responseContent);
                
                // 使用更严格的反序列化选项
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true, // 忽略属性名大小写
                    ReadCommentHandling = JsonCommentHandling.Skip,
                    AllowTrailingCommas = true,
                    DefaultIgnoreCondition = JsonIgnoreCondition.Never,
                    IncludeFields = true
                };
                
                // 尝试直接反序列化为FileTypesResponse列表
                List<FileTypeDto>? fileTypesResponse = null;
                try
                {
                    LogHelper.Debug("[GetFileTypesAsync] 开始反序列化JSON响应");
                    fileTypesResponse = JsonSerializer.Deserialize<List<FileTypeDto>>(responseContent, options);
                    LogHelper.Debug("[GetFileTypesAsync] 反序列化完成");
                }
                catch (JsonException ex)
                {
                    LogHelper.Error($"[GetFileTypesAsync] 内部JSON反序列化失败: {ex.Message}");
                    // 尝试直接反序列化为更通用的格式进行调试
                    try
                    {
                        var rawData = JsonSerializer.Deserialize<object>(responseContent);
                        LogHelper.Debug("[GetFileTypesAsync] 原始响应数据: " + JsonSerializer.Serialize(rawData));
                    }
                    catch (Exception innerEx)
                    {
                        LogHelper.Error("[GetFileTypesAsync] 无法解析原始响应数据: " + innerEx.Message);
                    }
                }
                
                var result = new List<TypesModel>();
                if (fileTypesResponse != null && fileTypesResponse.Count > 0)
                {
                    foreach (var fileType in fileTypesResponse)
                    {
                        result.Add(new TypesModel
                        {
                            FileTypeID = (int)fileType.Id,
                            FileTypeName = fileType.TypeName,
                            MemoryStrength = fileType.MemoryStrength
                        });
                    }
                }
                
                return result;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"获取文件类型时发生错误: {ex.Message}");
                return new List<TypesModel>();
            }
        }
        
        // 根据用户名获取文件类型
        public async Task<List<TypesModel>> GetFileTypesByUserAsync(string username)
        {
            string responseContent = string.Empty;
            try
            {
                LogHelper.Debug($"[GetFileTypesByUserAsync] 正在调用API: file/types/user/{username}, BaseUrl: " + _httpClient.BaseAddress);
                
                // 调用API获取指定用户的文件类型
                // 修复URL构建：BaseUrl已经包含""，所以这里不需要再加
                var url = $"file/types/user/{username}";
                var response = await _httpClient.GetAsync(url);
                
                if (!response.IsSuccessStatusCode)
                {
                    LogHelper.Warn($"[GetFileTypesByUserAsync] API调用失败: StatusCode={response.StatusCode}, Reason={response.ReasonPhrase}");
                    return new List<TypesModel>();
                }
                
                // 读取响应内容
                responseContent = await response.Content.ReadAsStringAsync();
                LogHelper.Debug("[GetFileTypesByUserAsync] API响应内容: " + responseContent);
                
                // 使用相同的反序列化选项
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                    ReadCommentHandling = JsonCommentHandling.Skip,
                    AllowTrailingCommas = true,
                    DefaultIgnoreCondition = JsonIgnoreCondition.Never,
                    IncludeFields = true
                };
                
                // 反序列化为文件类型列表
                List<FileTypeDto>? fileTypesResponse = null;
                try
                {
                    LogHelper.Debug("[GetFileTypesByUserAsync] 开始反序列化JSON响应");
                    fileTypesResponse = JsonSerializer.Deserialize<List<FileTypeDto>>(responseContent, options);
                    LogHelper.Debug("[GetFileTypesByUserAsync] 反序列化完成");
                }
                catch (JsonException ex)
                {
                    LogHelper.Error($"[GetFileTypesByUserAsync] 内部JSON反序列化失败: {ex.Message}");
                }
                
                var result = new List<TypesModel>();
                if (fileTypesResponse != null && fileTypesResponse.Count > 0)
                {
                    foreach (var fileType in fileTypesResponse)
                    {
                        result.Add(new TypesModel
                        {
                            FileTypeID = (int)fileType.Id,
                            FileTypeName = fileType.TypeName,
                            MemoryStrength = fileType.MemoryStrength
                        });
                    }
                }
                
                return result;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"获取用户文件类型时发生错误: {ex.Message}");
                return new List<TypesModel>();
            }
        }

        /// <summary>
        /// 根据用户ID获取文件类型
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户的文件类型列表</returns>
        public async Task<List<TypesModel>> GetFileTypesByUserIdAsync(int userId)
        {
            string responseContent = string.Empty;
            try
            {
                LogHelper.Debug("[GetFileTypesByUserIdAsync] 正在调用API: file/types/user/id/" + userId + ", BaseUrl: " + _httpClient.BaseAddress);
                
                // 调用API获取指定用户ID的文件类型
                // 修复URL构建：BaseUrl已经包含""，所以这里不需要再加
                var url = "file/types/user/id/" + userId;
                var response = await _httpClient.GetAsync(url);
                
                if (!response.IsSuccessStatusCode)
                {
                    LogHelper.Warn("[GetFileTypesByUserIdAsync] API调用失败: StatusCode=" + response.StatusCode + ", Reason=" + response.ReasonPhrase);
                    return new List<TypesModel>();
                }
                
                // 读取响应内容
                responseContent = await response.Content.ReadAsStringAsync();
                LogHelper.Debug("[GetFileTypesByUserIdAsync] API响应内容: " + responseContent);
                
                // 使用相同的反序列化选项
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                    ReadCommentHandling = JsonCommentHandling.Skip,
                    AllowTrailingCommas = true,
                    DefaultIgnoreCondition = JsonIgnoreCondition.Never,
                    IncludeFields = true
                };
                
                // 反序列化为文件类型列表
                List<FileTypeDto> fileTypesResponse = null;
                try
                {
                    LogHelper.Debug("[GetFileTypesByUserIdAsync] 开始反序列化JSON响应");
                    fileTypesResponse = JsonSerializer.Deserialize<List<FileTypeDto>>(responseContent, options);
                    LogHelper.Debug("[GetFileTypesByUserIdAsync] 反序列化完成");
                }
                catch (JsonException ex)
                {
                    LogHelper.Error("[GetFileTypesByUserIdAsync] 内部JSON反序列化失败: " + ex.Message);
                }
                
                var result = new List<TypesModel>();
                if (fileTypesResponse != null && fileTypesResponse.Count > 0)
                {
                    foreach (var fileType in fileTypesResponse)
                    {
                        result.Add(new TypesModel
                        {
                            FileTypeID = (int)fileType.Id,
                            FileTypeName = fileType.TypeName,
                            MemoryStrength = fileType.MemoryStrength
                        });
                    }
                }
                
                return result;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取用户文件类型时发生错误: " + ex.Message);
                return new List<TypesModel>();
            }
        }

        /// <summary>
        /// 通过服务器获取timestamp表的全部信息
        /// </summary>
        /// <returns>文件信息列表</returns>
        public async Task<List<TimeStampModel>> GetFilesAsync()
        {
            try
            {
                LogHelper.Debug("[GetFilesAsync] 正在调用API: file, BaseUrl: " + _httpClient.BaseAddress);
                
                // 修复URL构建：BaseUrl已经包含""，所以这里不需要再加
                var url = "file";
                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadFromJsonAsync<List<FileWithLastTimestampDto>>();
                    
                    if (result != null)
                    {
                        // 将服务器返回的格式转换为TimeStampModel列表
                        return result.Select(file => new TimeStampModel
                        {
                            FileID = (int)file.Id,
                            FileName = file.FileName,
                            FilePath = file.SavedPath,
                            TypeID = (int)file.FileTypeId,
                            TypeName = file.FileTypeName,
                            Time = file.LastTimestamp?.Time ?? DateTime.MinValue,
                            OpenTime = file.LastTimestamp?.OpenTime ?? DateTime.MinValue
                        }).ToList();
                    }
                }
                else
                {
                    LogHelper.Error($"获取文件列表失败: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"获取文件列表时发生异常: {ex.Message}");
            }
            
            return new List<TimeStampModel>();
        }
        
        /// <summary>
        /// 根据用户名获取文件信息
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>用户的文件信息列表</returns>
        public async Task<List<TimeStampModel>> GetFilesByUserAsync(string userid)
        {
            try
            {
                LogHelper.Debug($"[GetFilesByUserAsync] 正在调用API: file/user/{userid}, BaseUrl: " + _httpClient.BaseAddress);
                
                // 修复URL构建：BaseUrl已经包含""，所以这里不需要再加
                var url = $"file/user/{userid}";
                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadFromJsonAsync<List<FileWithLastTimestampDto>>();
                    
                    if (result != null)
                    {
                        // 将服务器返回的格式转换为TimeStampModel列表
                        return result.Select(file => new TimeStampModel
                        {
                            FileID = (int)file.Id,
                            FileName = file.FileName,
                            FilePath = file.SavedPath,
                            TypeID = (int)file.FileTypeId,
                            TypeName = file.FileTypeName,
                            Time = file.LastTimestamp?.Time ?? DateTime.MinValue,
                            OpenTime = file.LastTimestamp?.OpenTime ?? DateTime.MinValue
                        }).ToList();
                    }
                }
                else
                {
                    LogHelper.Error($"获取用户文件列表失败: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"获取用户文件列表时发生异常: {ex.Message}");
            }
            
            return new List<TimeStampModel>();
        }

        public async Task<bool> AddFileAsync(TimeStampModel fileInfo)
        {
            try
            {
                var url = "file/add";
                
                // 处理UserId的类型转换，从string转换为int?
                int? userId = null;
                if (!string.IsNullOrEmpty(fileInfo.UserId) && int.TryParse(fileInfo.UserId, out int parsedUserId))
                {
                    userId = parsedUserId;
                }
                
                // 创建与服务器期望的AddFileRequest格式匹配的对象
                // 注意：服务器端AddFileRequest.UserId已修改为int?类型，用于匹配UserInfo.Id
                var requestBody = new
                {
                    FileName = fileInfo.FileName,
                    SavedPath = fileInfo.FilePath,  // 映射FilePath到SavedPath
                    FileTypeId = (long)fileInfo.TypeID,  // 转换TypeID为long类型的FileTypeId
                    UserId = userId,  // 使用转换后的int?类型
                    FtpPath = fileInfo.FTPPath,  // 映射FTPPath到FtpPath
                    Time = fileInfo.Time,
                    OpenTime = fileInfo.OpenTime
                };
                
                var jsonContent = new StringContent(
                    System.Text.Json.JsonSerializer.Serialize(requestBody),
                    System.Text.Encoding.UTF8,
                    "application/json");
                
                var response = await _httpClient.PostAsync(url, jsonContent);
                
                if (response.IsSuccessStatusCode)
                {
                    return true;
                }
                else
                {
                    LogHelper.Error($"添加文件失败: {response.StatusCode}");
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"添加文件时发生异常: {ex.Message}");
                return false;
            }
        }

        public async Task<bool> AddTimestampAsync(TimeStampModel timeStampModel)
        {
            try
            {
                LogHelper.Debug($"[AddTimestampAsync] 正在调用API: file/timestamp");
                
                var url = "file/timestamp";
                // 创建只包含需要的字段的对象
                var timestampData = new
                {
                    FileId = timeStampModel.FileID,
                    Time = timeStampModel.Time,
                    OpenTime = timeStampModel.OpenTime
                };
                
                var response = await _httpClient.PostAsJsonAsync(url, timestampData);
                
                if (response.IsSuccessStatusCode)
                {
                    LogHelper.Debug("[AddTimestampAsync] 添加时间戳成功");
                    return true;
                }
                else
                {
                    LogHelper.Error($"添加时间戳失败: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"添加时间戳时发生异常: {ex.Message}");
            }
            
            return false;
        }

        public async Task<ReviewInfoResponse?> GetReviewInfoAsync(long fileId)
        {
            try
            {
                var url = $"file/timestamps/{fileId}";
                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadFromJsonAsync<ReviewInfoResponse>();
                }
                else
                {
                    LogHelper.Error($"获取文件时间戳信息失败: {response.StatusCode}");
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"获取文件时间戳信息时发生异常: {ex.Message}");
                return null;
            }
        }

        // 根据文件类型ID获取文件类型信息
        public async Task<TypesModel?> GetFileTypeByIdAsync(int fileTypeId)
        {
            try
            {
                var url = $"file/types/{fileTypeId}";
                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var fileTypeDto = await response.Content.ReadFromJsonAsync<FileTypeDto>();
                    if (fileTypeDto != null)
                    {
                        return new TypesModel
                        {
                            FileTypeID = (int)fileTypeDto.Id,
                            FileTypeName = fileTypeDto.TypeName,
                            MemoryStrength = fileTypeDto.MemoryStrength
                        };
                    }
                }
                else
                {
                    LogHelper.Error($"获取文件类型信息失败: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"获取文件类型信息时发生异常: {ex.Message}");
            }
            return null;
        }

        public async Task<bool> AddFileTypeAsync(TypesModel typeModel)
        {
            try
            {
                LogHelper.Info("开始添加文件类型...");
                LogHelper.Debug($"文件类型名称: {typeModel.FileTypeName}, 记忆强度: {typeModel.MemoryStrength}, 用户ID: {typeModel.UserId}");

                var request = new AddFileTypeRequest
                {
                    TypeName = typeModel.FileTypeName,
                    MemoryStrength = typeModel.MemoryStrength,
                    UserId = typeModel.UserId // 添加用户ID
                };

                var requestJson = System.Text.Json.JsonSerializer.Serialize(request);
                LogHelper.Debug($"请求JSON: {requestJson}");
                LogHelper.Debug($"请求URL: {ApiBaseUrl}file/types");

                var response = await _httpClient.PostAsJsonAsync("file/types", request);
                
                if (response.IsSuccessStatusCode)
                {
                    LogHelper.Info("文件类型添加成功");
                    return true;
                }
                else
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    LogHelper.Error($"添加文件类型失败: HTTP状态码 {response.StatusCode}");
                    LogHelper.Debug($"响应内容: {responseContent}");
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"添加文件类型时发生异常: {ex.Message}");
                LogHelper.Debug($"异常堆栈: {ex.StackTrace}");
                LogHelper.Debug($"内部异常: {ex.InnerException?.Message}");
                return false;
            }
        }

        public async Task<bool> DeleteFileTypeAsync(int fileTypeId)
        {
            try
            {
                var url = $"file/types/{fileTypeId}";
                var response = await _httpClient.DeleteAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    LogHelper.Info("文件类型删除成功");
                    return true;
                }
                else
                {
                    var content = await response.Content.ReadAsStringAsync();
                    LogHelper.Error($"文件类型删除失败: {response.StatusCode}, 内容: {content}");
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"删除文件类型时发生异常: {ex.Message}");
                return false;
            }
        }

        public async Task<bool> UpdateFileTypeAsync(TypesModel typeModel)
        {
            // 方法实现...
            return false;
        }

        public async Task<bool> DeleteFileAsync(int fileId)
        {
            try
            {
                var url = $"file/delete/{fileId}";
                var response = await _httpClient.DeleteAsync(url);
                return response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"删除文件时发生异常: {ex.Message}");
                return false;
            }
        }

       
    }

    // 辅助类和模型
    public class LoginResult
    {
        public bool Success { get; set; }
        public string ErrorMessage { get; set; } = string.Empty;
        public MauiApp.Models.UserDto User { get; set; } = new MauiApp.Models.UserDto();
    }

    // 使用Models文件夹中的LoginResponse类，不再重复定义
    public class LoginResponse
    {
        public bool Success { get; set; }
        public string Message { get; set; } = string.Empty;
        public string Token { get; set; } = string.Empty;
        public MauiApp.Models.UserDto User { get; set; } = new MauiApp.Models.UserDto();
    }

    public class FileTypeDto
    {
        public long Id { get; set; }
        public string TypeName { get; set; } = string.Empty;
        public double MemoryStrength { get; set; }
    }

    public class TimestampResponse
    {
        public long Id { get; set; }
        public DateTime Time { get; set; }
        public DateTime OpenTime { get; set; }
    }

    public class FileWithLastTimestampResponse
    {
        public long Id { get; set; }
        public string FileName { get; set; } = string.Empty;
        public string SavedPath { get; set; } = string.Empty;
        public string FtpPath { get; set; } = string.Empty;
        public long FileTypeId { get; set; }
        public string FileTypeName { get; set; } = string.Empty;
        public TimestampResponse? LastTimestamp { get; set; }
    }

    public class AddFileRequest
    {
        public string FileName { get; set; } = string.Empty;
        public string SavedPath { get; set; } = string.Empty;
        public long FileTypeId { get; set; }
    }

    public class AddTimestampRequest
    {
        public DateTime? Time { get; set; }
        public DateTime? OpenTime { get; set; }
    }

    public class AddFileTypeRequest
    {
        public string TypeName { get; set; } = string.Empty;
        public double MemoryStrength { get; set; }
        public string UserId { get; set; } = string.Empty;
    }
}